//
//  YSHomeViewController.m
//  HubayMe1
//
//  Created by apple on 16/12/16.
//  Copyright © 2016年 Global Barter. All rights reserved.
//

#import "YSHomeViewController.h"
#import "SDCycleScrollView.h"
#import "YSRecommendedProductsCell.h"
#import "CJDingDanButton.h"
#import "YSJinRiTuiJianButton.h"



#import "PYSearch.h"
#import "YSSearchListViewController.h"

static CGFloat const margin = 10;
static NSInteger const cols = 2;
#define wh ((kScreenWidth - (cols - 1) * margin) / cols)


static NSString * const ID = @"RecommendedProductsCell";

@interface YSHomeViewController ()<UITableViewDataSource , UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate,PYSearchViewControllerDelegate>
@property (nonatomic, strong)  UICollectionView *collectionView;

@property (strong ,nonatomic) UITableView *tableView;

@property (strong ,nonatomic) UISearchBar *searchBar;
@end

@implementation YSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setUpTableView];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem item:[UIImage imageNamed:@"bunnerTu"] highImageLimit:[UIImage imageNamed:@"bunnerTu"] target:self action:@selector(xiaoxi)];
    self.tableView.showsVerticalScrollIndicator = NO;
    //1 设置头部View
    [self setUpTableTopView];
    
    //2 设置底部的View
    [self setUpBottomView];
    
    [self setUpTitleView];
}

-(void)setUpTableView{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    //self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    self.tableView.dataSource =self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
}
-(void)xiaoxi{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你想要获取消息吗?" message:@"点击取消将会不获取" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
       textField.placeholder = @"文本框占位文字";
    }];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self toast:@"取消"];
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textF = alertController.textFields.lastObject;
        
        [self toast:textF.text];
    }];
    
    [alertController addAction:action];
    [alertController addAction:action1];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}
-(void)setUpTitleView{
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth -300, 30)];
    searchBar.delegate = self;
    self.searchBar = searchBar;
    //    searchBar.barStyle = UIBarStyleBlack;
//        searchBar.backgroundColor = GRJColor(240, 240, 240);
    searchBar.placeholder = @"搜索药品/品牌/症状";
    
    // 是否显示右侧的“书图标”
    //searchBar.showsBookmarkButton = YES;
    // 是否显示取消按钮
    // 是否显示搜索结果按钮
    //searchBar.showsSearchResultsButton  = YES;
    // 设置键盘样式
    //[self.searchBar setKeyboardType:UIKeyboardTypeNumberPad];
    
    
    //2 设置分栏条
//    // 是否显示分栏条
//    [self.searchBar setShowsScopeBar:YES];
//    // 分栏条，栏目
//    [self.searchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"Singer",@"Song",@"Album", nil]];
//    // 分栏条的背景颜色
//    [self.searchBar setScopeBarBackgroundImage:[UIImage imageNamed:@"bunnerTu"]];
//    // 分栏条默认选中的按钮的下标
//    [self.searchBar setSelectedScopeButtonIndex:1];

    searchBar.tintColor = [UIColor darkGrayColor];
    
    self.navigationItem.titleView =searchBar;
}

#pragma mark 搜索
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
//    searchBar.showsCancelButton = YES;
//    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
//        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
//            UIButton * cancel =(UIButton *)view;
//            [cancel setTitle:@"搜索" forState:UIControlStateNormal];
//            cancel.titleLabel.font = [UIFont systemFontOfSize:14];
//            cancel.backgroundColor = [UIColor whiteColor];
//            [cancel setTitleColor:GRJMainColor forState:UIControlStateNormal];
//            cancel.layer.cornerRadius = 3;
//            
//        }
//    }

    // 1.创建热门搜索
    NSArray *hotSeaches = @[@"Java", @"Python", @"Objective-C", @"Swift", @"C", @"C++", @"PHP", @"C#", @"Perl", @"Go", @"JavaScript", @"R", @"Ruby", @"MATLAB"];
    // 2. 创建控制器
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSeaches searchBarPlaceholder:@"搜索编程语言" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        // 开始搜索执行以下代码
        // 如：跳转到指定控制器
        [searchViewController dismissViewControllerAnimated:YES completion:nil];
        
        [self pushSearchViewC:searchText];
    }];
    // 3. 设置风格
                // 选择热门搜索
    searchViewController.hotSearchStyle = 1; // 热门搜索风格根据选择
        searchViewController.searchHistoryStyle = PYHotSearchStyleDefault; // 搜索历史风格为default
            // 选择搜索历史
//        searchViewController.hotSearchStyle = PYHotSearchStyleDefault; // 热门搜索风格为默认
//        searchViewController.searchHistoryStyle = (NSInteger)indexPath.row; // 搜索历史风格根据选择
    // 4. 设置代理
    searchViewController.delegate = self;
    // 5. 跳转到搜索控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:nav  animated:NO completion:nil];
    
}
-(void)pushSearchViewC:(NSString *)searchText{
    YSSearchListViewController *modalViewC = [[YSSearchListViewController alloc] init];
    modalViewC.view.backgroundColor = [UIColor whiteColor];
    modalViewC.title = searchText;
    [self.navigationController pushViewController:modalViewC animated:YES];
}

#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        // 根据条件发送查询（这里模拟搜索）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 搜索完毕
            // 显示建议搜索结果
            NSMutableArray *searchSuggestionsM = [NSMutableArray array];
            for (int i = 0; i < arc4random_uniform(5) + 10; i++) {
                NSString *searchSuggestion = [NSString stringWithFormat:@"搜索建议 %d", i];
                [searchSuggestionsM addObject:searchSuggestion];
            }
            // 返回
            searchViewController.searchSuggestions = searchSuggestionsM;
        });
    }
}
//监听键盘点击搜索
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
    [self.searchBar resignFirstResponder];
    [self toast:@"搜索并推掉键盘"];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
    [self.searchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    return YES;
}
#define SDCycleScrollViewHeight  kScreenWidth * 350 / 750
-(void)setUpTableTopView{
    
    // 网络加载图片的轮播器
    //SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, SDCycleScrollViewHeight) delegate:nil placeholderImage:[UIImage imageNamed:@"scrollViewImage"]];
    
    // 本地加载图片
    NSArray *imageArr = @[@"bunnerTu",@"bunnerTu",@"bunnerTu"];
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, SDCycleScrollViewHeight) imageNamesGroup:imageArr];
    
    //NSLog(@"%@",NSStringFromCGRect(cycleScrollView.frame));
    
    //    cycleScrollView.titlesGroup =self.titleArray;
    //    cycleScrollView.imageURLStringsGroup = self.imageArray;
    //    cycleScrollView.delegate = self;
    
//    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.tableView.tableHeaderView = cycleScrollView;
    
}

-(void)setUpBottomView{
    
    // tableView的底部视图 也属于tableView内容一部分
    
    // 创建布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置cell尺寸
    
    layout.itemSize = CGSizeMake(wh, wh+30);
    layout.minimumInteritemSpacing = margin;
    layout.minimumLineSpacing = margin;
    
    // 创建UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, wh*10 + 50*12) collectionViewLayout:layout];
    _collectionView = collectionView;
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = GRJColor(240, 240, 240);
    
    // 注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"YSRecommendedProductsCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    
    // 设置tableView底部视图
    self.tableView.tableFooterView = collectionView;
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 19;
}


#pragma mark - UICollectionViewDelegate
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YSRecommendedProductsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    return cell;
}

// 点击cell就会调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    
    if (indexPath.section == 0) {
        
        [cell.contentView addSubview:[self set0ViewCell]];
        
    }else if (indexPath.section == 1) {
        
        [cell.contentView addSubview:[self set1ViewCell]];
        
    }else if (indexPath.section == 2) {
        
        [cell.contentView addSubview:[self set2ViewCell]];
        
    }else if (indexPath.section == 3) {
        
        [cell.contentView addSubview:[self set3ViewCell]];
        cell.userInteractionEnabled = NO;
        cell.backgroundColor = GRJColor(247, 247, 247);
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }
    else{
        return 0.1;
    }
}
-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 80;
    }else if(indexPath.section==1){
        return 44;
    }else if(indexPath.section==2){
        return 200;
    }else{
        return 40;
    }
}
-(UIView *)set0ViewCell{
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenWidth, 80);
    
    CGFloat buttonW = kScreenWidth/4;
    
    for (int i = 0; i < 4; i++) {
        CJDingDanButton *button = [[CJDingDanButton alloc]init];
        button.frame = CGRectMake(i*buttonW, 0, buttonW, view.height);
        [button setImage:[UIImage imageNamed:@"bunnerTu"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.titleLabel.font = FONT_13;
        [button setTitle:@"生活消费" forState:UIControlStateNormal];
        [view addSubview:button];
    }
    
    
    return view;
}
-(UIView *)set1ViewCell{
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenWidth, 44);
    
    [view addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAddver)]];
    
    UIImageView *imageV = [[UIImageView alloc]init];
    imageV.image = [UIImage imageNamed:@"bunnerTu"];
    imageV.frame = CGRectMake(10, 10, 24, 24);
    [view addSubview:imageV];
    
    
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = [UIColor lightGrayColor];
    lineView.frame = CGRectMake(35, 10, 1, 24);
    [view addSubview:lineView];
    
    UILabel *labelText = [[UILabel alloc]init];
    labelText.text  = @"广州冬季易货节马上开始了,快快报名吧!";
    labelText.frame = CGRectMake(40, 15, kScreenWidth-35 -40, 15);
    labelText.font = FONT_15;
    labelText.textColor = [UIColor redColor];
    [view addSubview:labelText];
    
    UILabel *badgeValue = [[UILabel alloc]init];
    badgeValue.frame = CGRectMake(kScreenWidth-35, 10, 15, 15);
    badgeValue.text= @"1";
    badgeValue.textColor = [UIColor whiteColor];
    badgeValue.backgroundColor = GRJMainColor;
    badgeValue.textAlignment = NSTextAlignmentCenter;
    badgeValue.font = FONT_12;
    [view addSubview:badgeValue];
    
    return view;
}
-(void)tapAddver{
    NSLog(@"点了广告");
}
-(UIView *)set2ViewCell{
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenWidth, 200);
    
    UIView *topView = [[UIView alloc]init];
    topView.frame = CGRectMake(0, 0, kScreenWidth, 44);
    [view addSubview:topView];
    
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(10, 15, 2, 14);
    lineView.backgroundColor = [UIColor blueColor];
    [topView addSubview:lineView];
    
    UILabel *topTextL = [[UILabel alloc]init];
    topTextL.text = @"今日推荐";
    topTextL.frame  = CGRectMake(20, 15, 100, 14);
    topTextL.font = FONT_14;
    [topView addSubview:topTextL];
    
    [topView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAddver)]];
    
    
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.frame = CGRectMake(0, 44, kScreenWidth, 156);
    [view addSubview:bottomView];
    
    CGFloat buttonW = kScreenWidth/3;
    
    for (int i = 0; i < 3; i++) {
        YSJinRiTuiJianButton *button = [[YSJinRiTuiJianButton alloc]init];
        button.frame = CGRectMake(i*buttonW, 0, buttonW, bottomView.height);
        [button setImage:[UIImage imageNamed:@"bunnerTu"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.titleLabel.font = FONT_13;
        [button setTitle:@"生活消费" forState:UIControlStateNormal];
        [bottomView addSubview:button];
    }
    
    return view;
}
-(UIView *)set3ViewCell{
    
    CGFloat lableX = kScreenWidth/2 - 30;
    CGFloat lineViewWidth = 80;
    
    UIView *back1 = [[UIView alloc]init];
    back1.backgroundColor = [UIColor groupTableViewBackgroundColor];
    back1.frame = CGRectMake(0, 0, kScreenWidth, 40);
    
    
    UIView *view1 = [[UIView alloc]init];
    view1.backgroundColor = GRJColor(217, 217, 217);
    view1.frame = CGRectMake(lableX - lineViewWidth, 15+7.5, lineViewWidth, 1);
    [back1 addSubview:view1];
    
    UIView *view2 = [[UIView alloc]init];
    view2.backgroundColor = GRJColor(217, 217, 217);
    view2.frame = CGRectMake(lableX + 70, 15+7.5, lineViewWidth, 1);
    [back1 addSubview:view2];
    
    UILabel *textL = [[UILabel alloc]init];
    textL.frame = CGRectMake(lableX, 15, 70, 15);
    textL.text = @"市场采买";
    textL.font = FONT_15;
    textL.textAlignment = NSTextAlignmentCenter;
    [back1 addSubview:textL];
    
    return back1;
}

@end
